<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <el-form-item v-if="this.currentStep=='a'|| this.currentStep=='b'|| this.currentStep=='c'|| this.currentStep=='d'">
              <el-button type="primary" @click="showAddForm">下发照片视频任务</el-button>
            </el-form-item>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="nickName"
        label="任务接收者"
        min-width="40">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        min-width="40">
        <template scope="scope">
          {{statusDate(scope.row.status)}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="msg"
        label="信息"
        min-width="100">
      </el-table-column> -->
      <el-table-column
        prop="content"
        label="任务内容"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="任务下发时间"
        min-width="100">
        <template scope="scope">
          {{fmtDate(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="uploadingTime"
        label="上传时间"
        min-width="100">
        <template scope="scope">
          {{fmtDate(scope.row.uploadingTime)}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="picNum"
        label="照片数量"
        min-width="30">
      </el-table-column>
      <el-table-column
        prop="videoNum"
        label="视频数量"
        min-width="30">
      </el-table-column> -->

      <el-table-column
        prop="address"
        label="操作"
        min-width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showFile(scope.$index, scope.row)">显示内容</el-button>
          <el-button size="mini" type="primary" @click="downloadByBlob(scope.row.url, scope.row.nickName)">全部下载</el-button>
          <!-- <el-button size="mini" type="primary" v-if="scope.row.status==3||scope.row.status==4?true:false"  @click="handleEdit(scope.$index, scope.row)">重新上传</el-button>
          <el-button size="mini" type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog title="下发照片视频任务" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">

        <el-form-item label="下发给" label-width="100px" prop="userId">
          <el-select v-model="editForm.userId" placeholder="请选择" style="width: 90%;" >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="照片数量" label-width="100px">
          <el-input-number v-model="editForm.picNum" size="mini" style="width: 100px;" controls-position="right" :min="0" :max="100" label=""></el-input-number>
        </el-form-item>
        <el-form-item label="视频数量" label-width="100px">
          <el-input-number v-model="editForm.videoNum" size="mini" style="width: 100px;" controls-position="right" :min="0" :max="100" label=""></el-input-number>
        </el-form-item> -->
        <el-form-item label="任务内容" label-width="100px" prop="content">
          <el-input v-model="editForm.content" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">下发</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog title='图片预览'  :visible.sync="imgDialogVisible" width="650px">
      <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
      <table class="test-item-table">
      <tr>
        <th>图片/视频</th>
        <!-- <th v-if="!onlyNext">
          选择
          <el-button type="primary" size="mini" plain @click.native.prevent="">全选</el-button>
        </th> -->
      </tr>
      <tr>
        <td>
      <template v-for="(item,index) in picFiles">
        <el-image
            style="width: 500px;margin-top: 8px;"
            :src="fileBaseUrl + item"
            :preview-src-list="[fileBaseUrl + item]"
            v-if="!isVideo(item)">
          </el-image>
      </template>
      <template v-for="(item,index) in videoFiles">
        <div style="margin-top: 8px;">
        <video width="500px" :src="fileBaseUrl + item" alt="" controls="controls" v-if="isVideo(item)">
          您的浏览器无法播放视频
        </video>
        </div>
      </template>
      </td>
      <!-- <td v-if="!onlyNext">
        <input v-model="doneForm.doneTaskItemIds" type="checkbox" :value="item.id" />
      </td> -->
      </tr>
      </table>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="imgDialogVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click.native.prevent="itemSelectAll">全选</el-button> -->
        <!-- <el-button type="primary" @click="downloadByBlob(fileBaseUrl + item, 123)">全部下载</el-button> -->
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getMyTaskPvList, addMyTaskPv, getTestOrderTaskPvFileList} from "../../../api/test_order_task.js";
import {getAllTestSiteList} from '../../../api/test_site.js'
import {getToken} from '../../../common/utils/auth.js'
import {getTestCarList} from '../../../api/test_car.js'
import {getFileUrl} from '../../../api/file.js'
import {getAllUserList} from '../../../api/user.js'

export default {
  name: "testTaskPvManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      currentStep:'',
      searchForm:{

      },

      editFormVisible:false,
      loading: false,
      editForm: {
        id:0,
        taskTid: '',
        content: '',
        picNum: 0,
        videoNum: 0,
        userId:'',
      },
      editRules: {
        userId: [{ required: true, message:"请选择发送给谁", trigger: 'blur'}],
        content: [{ required: true, message:"请输入任务内容", trigger: 'blur'}],
      },

      loadingDiv: null,
      taskTid:'',
      userList:[],

      picFiles:[],
      videoFiles:[],
      imgDialogVisible:false,
    }
  },
  computed:{

  },
  mounted() {
    let taskTid=this.$route.params.taskTid;
    // console.log(this.$route.params)
    this.currentStep = this.$route.params.currentStep;
    this.taskTid = taskTid;

    this.init();

    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";

  },
  methods: {
    isVideo(val){
      if(util.isEmpty(val)){
        return false;
      }
      if(val.toLowerCase().indexOf(".avi") != -1 || val.toLowerCase().indexOf(".mp4") != -1){
        return true;
      }
      return false;
    },
    showFile(index,row){
      // console.log(row)
      if(util.isEmpty(row.url)){
        this.$message.error("未发现文件");
        return;
      }
      let fileTypeArr = row.fileType.split(",");
      let urlArr = row.url.split(",");
      let picFiles = [];
      let videoFiles = [];

      for(let i in fileTypeArr){
        if(fileTypeArr[i] == "1"){
          picFiles.push(urlArr[i]);
        }else if(fileTypeArr[i] == "2"){
          videoFiles.push(urlArr[i]);
        }
      }

      this.picFiles = picFiles;
      this.videoFiles = videoFiles;

      this.imgDialogVisible = true;
    },
    getFileUrl(){

    },

    // downloadByBlob(url,name) {
    //   if(util.isEmpty(url)){
    //     this.$message.error("未发现文件");
    //     return;
    //   }
    //   let urlArr = url.split(",");
    //   for(var i =0;i<urlArr.length;i++){
    //     let image = new Image()
    //     image.setAttribute('crossOrigin', 'anonymous')
    //     image.src = this.fileBaseUrl+urlArr.[i]
    //     image.onload = () => {
    //     let canvas = document.createElement('canvas')
    //     canvas.width = image.width
    //     canvas.height = image.height
    //     let ctx = canvas.getContext('2d')
    //     ctx.drawImage(image, 0, 0, image.width, image.height)
    //     canvas.toBlob((blob) => {
    //     let url = URL.createObjectURL(blob)
    //     // console.log(image.src)
    //     this.download(url,i)
    //     // 用完释放URL对象
    //     URL.revokeObjectURL(url)
    //         })
    //       }
    //   }

    //   },

    //   download(href, name) {
    //   let eleLink = document.createElement('a')
    //   eleLink.download = name
    //   eleLink.href = href
    //   eleLink.click()
    //   eleLink.remove()
    //   },

    downloadByBlob(url) {
      if(util.isEmpty(url)){
        this.$message.error("未发现文件");
        return;
      }
      let urlArr = url.split(",");
      for(var i =0;i<urlArr.length;i++){

        url = this.fileBaseUrl+urlArr.[i]
        // console.log(url)
        this.download(url,i)
        // 用完释放URL对象
      }
      },
      download(urls,i)
      {undefined
      fetch(urls).then((res) => {undefined
                          res.blob().then((blob) => {undefined
                              const url = window.URL.createObjectURL(blob)
                              const a = document.createElement('a')
                              a.href = url
                              a.download = i ;
                              a.click()
                              window.URL.revokeObjectURL(url)
                          })
                      })
                  },

    handleRemove(file, fileList) {
            // console.log(file, fileList);
          },
    handlePreview(file) {
            // console.log(file);
          },


    init(){
      // 获取所有用户列表
      getAllUserList().then(res => {
        if(res.code == 1) {
          this.userList = res.data;
        }
      }).catch(res => {

      });
    },


    isEmpty(val){
      return util.isEmpty(val);
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },
    statusDate(data){
      if(data==1){
        return "已完成";
      }else if(data==2){
        return "进行中";
      }else if(data==3){
        return "回退";
      }else if(data==4){
        return "流转";
      }
    },




    showAddForm() {
       this.editForm.content = '';
       this.editForm.userId = '';
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.last){
        this.editForm[key] = '';
      }

      this.editForm.taskTid = this.taskTid;
      this.editForm.picNum = 0;
      this.editForm.videoNum=0;
      this.editForm.id = 0;
      this.editFormVisible = true;

    },
    computed(){
      this.editForm.totalPrice = this.editForm.price*this.editForm.num

    },


    handleEdit(index, row) {
    // console.log(editForm.costOther)

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }
      this.editFormVisible = true;

      this.editForm.carName = this.editForm.carId

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {

          // if(this.editForm.picNum <=0 && this.editForm.videoNum<=0){
          //   this.$message.error("照片数量和视频数量不能同时为0");
          // }

          this.loading = true;
          let loadingText = "下发中...";
          const loadingDiv = util.showLoading(loadingText)

          addMyTaskPv(this.editForm).then(res => {
            let title = "下发"
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.content+"任务?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestOrderTaskPvList({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getMyTaskPvList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        taskTid: this.taskTid,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.total = data.total;
          this.tableData = data.dataList;
          // console.log(data);
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
      // console.log(this.url)
      // console.log(this.url.length)
      // getTestOrderTaskPvFileList()






    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .test-item-table{
    width: 80%;
    border-collapse: collapse;

    th, td {
      width: 33.3%;
      text-align: center;
      border: 1px solid #CCC;
    }
  }

  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 7%;
      text-align: center;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
</style>
